//
//  XHArticleNewsView.m
//  xinhua_sx
//
//  Created by 党阳阳 on 14-7-23.
//  Copyright (c) 2014年 dangyangyang. All rights reserved.
//

#import "XHArticleNewsView.h"

#import  <POP.h>
#import "ReactiveCocoa.h"
#import <RACEXTScope.h>
#import "dangeViewController.h"
#import "GTMDefines.h"
#import "GTMNSString+HTML.h"

@interface XHArticleNewsView ()
@property (nonatomic ,strong) UIButton *news1Button;
@property (nonatomic ,strong) UIButton *news2Button;
@property (nonatomic ,strong) UIScrollView *newsScrollView;
@property (nonatomic ,strong) UIImageView *slide;


@property (nonatomic ,strong) NSArray *news1Data;
@property (nonatomic ,strong) NSArray *news2Data;

@property (nonatomic, strong) UITableView* t1;
@property (nonatomic, strong) UITableView* t2;
@end

@implementation XHArticleNewsView
@synthesize t1 =_t1;
@synthesize t2 = _t2;
- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        _viewModel = [[XHArticleNewsViewModel alloc] init];
        _news1Data = [NSArray array];
        _news2Data = [NSArray array];
         NSUserDefaults* defa = [NSUserDefaults standardUserDefaults];
        _news1Data = [defa objectForKey:@"本地新闻"];
        _news2Data = [defa objectForKey:@"要闻推荐"];
        UIView *buttonView = [[UIView alloc] initWithFrame:CGRectMake(0, 5, frame.size.width, 30)];
        buttonView.backgroundColor = [UIColor whiteColor];
        //buttonView.backgroundColor = [UIColor colorWithRed:225.0/255 green:230.0/255 blue:236.0/255 alpha:1.0];
        _news1Button = [[UIButton alloc] initWithFrame:CGRectMake(40, 0, 80, 20)];
        _news1Button.backgroundColor = [UIColor whiteColor];
        [_news1Button setTitle:@"本地新闻" forState:UIControlStateNormal];
        _news1Button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_news1Button setTitleColor: [UIColor colorWithRed:127.0/255 green:149.0/255 blue:186.0/255 alpha:1.0] forState:UIControlStateNormal];
        _news1Button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
        [_news1Button addTarget:self action:@selector(didHitButton:) forControlEvents:UIControlEventTouchUpInside];
        
        _slide = [[UIImageView alloc] initWithFrame:CGRectMake(0, 26, 160, 2)];
        _slide.image = [UIImage imageNamed:@"slide.png"];
        _slide.contentMode = UIViewContentModeScaleToFill;
        //_slide.backgroundColor = [UIColor colorWithRed:14.0f/225.0f green:90.0f/255.0f blue:155.0f/255.0f alpha:1.0f];
        UIView* v13 = [[UIView alloc] initWithFrame:CGRectMake(0, 26, 310, 2)];
        v13.backgroundColor = [UIColor grayColor];
        [buttonView addSubview:v13];
        v13.alpha = 0.5;
        _news2Button = [[UIButton alloc] initWithFrame:CGRectMake(200, 0, 80, 20)];
        _news2Button.backgroundColor = [UIColor whiteColor];
        [_news2Button setTitle:@"要闻推荐" forState:UIControlStateNormal];
        _news2Button.titleLabel.textAlignment = NSTextAlignmentCenter;
        [_news2Button setTitleColor: [UIColor colorWithRed:127.0/255 green:149.0/255 blue:186.0/255 alpha:1.0] forState:UIControlStateNormal];
        _news2Button.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:15.0];
        [_news2Button addTarget:self action:@selector(didHitButton:) forControlEvents:UIControlEventTouchUpInside];

        [buttonView addSubview:_slide];
        [buttonView addSubview:_news1Button];
        [buttonView addSubview:_news2Button];
        [self addSubview:buttonView];
        
        _newsScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, buttonView.frame.size.height+buttonView.frame.origin.y+5, frame.size.width, frame.size.height-buttonView.frame.size.height-buttonView.frame.origin.y-5)];
        _newsScrollView.contentSize = CGSizeMake(_newsScrollView.frame.size.width*2, _newsScrollView.frame.size.height);
        _newsScrollView.pagingEnabled = YES;
        _newsScrollView.showsVerticalScrollIndicator = NO;
        _newsScrollView.showsHorizontalScrollIndicator = NO;
        _newsScrollView.delegate = self;
        
        UITableView *news1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _newsScrollView.frame.size.width, _newsScrollView.frame.size.height)];
        news1.dataSource = self;
        news1.delegate = self;
        news1.scrollEnabled = NO;
        news1.tag = 1010;
        news1.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        UITableView *news2 = [[UITableView alloc] initWithFrame:CGRectMake(_newsScrollView.frame.size.width, 0, _newsScrollView.frame.size.width, _newsScrollView.frame.size.height)];
        [_newsScrollView addSubview:news1];
        [_newsScrollView addSubview:news2];
        news2.dataSource = self;
        news2.delegate = self;
        news2.scrollEnabled = NO;
        news2.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        news2.tag = 1011;
        
        [self addSubview:_newsScrollView];
        
        _t1  =news1;
        _t2 = news2;
       
      /*  @weakify(self);
        [[_viewModel pullNews1] subscribeNext:^(id x) {
            @strongify(self);
            if ([x isKindOfClass:[NSDictionary class]]) {
                self.news1Data = nil;
                self.news1Data = [x objectForKey:@"content"];
                NSLog(@"本地 = %@",self.news1Data);
                NSUserDefaults* defa = [NSUserDefaults standardUserDefaults];
                if ([self.news1Data count] > 0)
                {
                    [defa removeObjectForKey:@"本地新闻"];
                    [defa  setObject:self.news1Data forKey:@"本地新闻"];
                    [defa  synchronize];
                    NSLog(@"本地新闻缓存成功");
                    
                }
              
                [news1 reloadData];
            }
            
        }];
        [[_viewModel pullNews2] subscribeNext:^(id x) {
            @strongify(self);
            if ([x isKindOfClass:[NSDictionary class]]) {
                self.news2Data = nil;
                self.news2Data = [x objectForKey:@"content"];
                NSUserDefaults* defa = [NSUserDefaults standardUserDefaults];
                if ([self.news2Data count] > 0)
                {
                
                    [defa removeObjectForKey:@"要闻推荐"];
                    [defa  setObject:self.news2Data forKey:@"要闻推荐"];
                    [defa  synchronize];
                    NSLog(@"要闻推荐缓存成功");
                    
                }
                [news2 reloadData];
            }
            
        }];*/
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/
-(void)reloadData2
{
    @weakify(self);
    [[_viewModel pullNews1] subscribeNext:^(id x) {
        @strongify(self);
        if ([x isKindOfClass:[NSDictionary class]]) {
            self.news1Data = nil;
            self.news1Data = [x objectForKey:@"content"];
            NSLog(@"本地 = %@",self.news1Data);
            NSUserDefaults* defa = [NSUserDefaults standardUserDefaults];
            if ([self.news1Data count] > 0)
            {
                [defa removeObjectForKey:@"本地新闻"];
                [defa  setObject:self.news1Data forKey:@"本地新闻"];
                [defa  synchronize];
                NSLog(@"本地新闻缓存成功");
                
            }
            
            [_t1 reloadData];
            
        }
        
    }];
    [[_viewModel pullNews2] subscribeNext:^(id x) {
        @strongify(self);
        if ([x isKindOfClass:[NSDictionary class]]) {
            self.news2Data = nil;
            self.news2Data = [x objectForKey:@"content"];
            NSUserDefaults* defa = [NSUserDefaults standardUserDefaults];
            if ([self.news2Data count] > 0)
            {
                
                [defa removeObjectForKey:@"要闻推荐"];
                [defa  setObject:self.news2Data forKey:@"要闻推荐"];
                [defa  synchronize];
                NSLog(@"要闻推荐缓存成功");
                
            }
            [_t2 reloadData];
        }
        
    }];
}
- (void)reloadView:(UITableView *)tableView
{
    NSLog(@"tableVIw reload");
    [tableView reloadData];
    [self setNeedsDisplay];
}
- (void)didHitButton:(UIButton *)sender
{
   
    CGFloat oX= sender.frame.origin.x;
    CGRect rect = _slide.frame;
    rect.origin.x= oX;
    POPBasicAnimation *slide = [POPBasicAnimation animationWithPropertyNamed:kPOPViewFrame];
    if ([sender isEqual:_news1Button]) {
        [_newsScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        rect.origin.x=0;
        [self.delegate pusdhyaowen1];
    }else{
        [_newsScrollView setContentOffset:CGPointMake(_newsScrollView.frame.size.width, 0) animated:YES];
        rect.origin.x=160;
        [self.delegate pusdhyaowen];
        
    }
    slide.toValue = [NSValue valueWithCGRect:rect];
    [_slide pop_addAnimation:slide forKey:@"slide"];

}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:_newsScrollView]){
       
        CGRect rect = _slide.frame;
        CGFloat oX = scrollView.contentOffset.x/2.0;
       
        rect.origin.x = oX;
        
        POPSpringAnimation *slide = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
        slide.toValue = [NSValue valueWithCGRect:rect];
        slide.springSpeed = 20;
        [_slide pop_addAnimation:slide forKey:@"slide"];
    }

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 25.0;
    
}

#pragma mark tableView datasource


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag==1010) {
        return [_news1Data count];
    }
    return [_news2Data count];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *data;
    if (tableView.tag == 1010) {
        data = self.news1Data;
    }
    if (tableView.tag == 1011) {
        data = self.news2Data;
    }
    
    
    
    static NSString *CellIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
        cell.textLabel.textColor = [UIColor blackColor];
        
    }
    if ([data count]>0) {
        
        cell.textLabel.text = [[data objectAtIndex:indexPath.row] objectForKey:@"title"];
        cell.textLabel.text = [cell.textLabel.text gtm_stringByUnescapingFromHTML];
        cell.tag = [[[data objectAtIndex:indexPath.row] objectForKey:@"id"] intValue];
        NSLog(@"newID = %@",[[data objectAtIndex:indexPath.row] objectForKey:@"id"]);
    }
    cell.imageView.image = [UIImage imageNamed:@"homepage_listview_item_point"];
    return cell;
    
}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"cell.tag = %d",cell.tag);
    NSString* imagestring;
    if (tableView.tag == 1010) {
        
        imagestring = self.news1Data[indexPath.row][@"image"];
    }
    if (tableView.tag == 1011) {
          imagestring = self.news2Data[indexPath.row][@"image"];
    }
    NSLog(@"table1 = %@",imagestring);
    if ([imagestring length] > 0 && ![imagestring isEqualToString:@"null"])
    {
        if([imagestring hasPrefix:@"http"])
        {
            
            imagestring =  [NSString stringWithFormat:@"%@",imagestring];
            
            
        }
        else
        {
            imagestring = [NSString stringWithFormat:@"http://183.203.18.45:7001%@",imagestring];
            
        }
        
    }
    NSLog(@"imageset = %@",imagestring);
    [self.delegate selectArticleWithNewsId:[NSNumber numberWithInteger:cell.tag] withImageString:imagestring];
    
    
}
@end
